#include <iostream>
#include <cstdlib>
#include <unistd.h>
using namespace std;


//封装成函数
bool GetQueryString(std::string& query_string)
{
  bool result = false;
  std::string method = getenv("NETHOD");
  if(method=="GET")
  {
    query_string = getenv("QUERY_STRING");
    result = true;
  }
  else if(method=="POST"){
    int content_length = atoi(getenv("CONTENT_LENGTH"));
    char c = 0;
    while(content_length)
    {
      read(0, &c, 1);
      query_string.push_back(c);
      content_length--;
    }
    result = true;
  }
  else{
    result = false;
  }

  return result;
}

void CutString(string &in, const string &sep, string &out1, string &out2)
{
  auto pos = in.find(sep);
  if(string::npos != pos)
  {
    out1 = in.substr(0, pos);
    out2 = in.substr(pos+sep.size());
  }
}


int main()
{
  string query_string;
  GetQueryString(query_string);

  //切割获取的正文
  string str1;
  string str2;
  CutString(query_string, "&", str1, str2);

  string name1;
  string value1;
  CutString(str1, "=", name1, value1);

  string name2;
  string value2;
  CutString(str2, "=", name2, value2);

  //输出到fd1
  cout << name1 << " : " << value1 << endl;
  cout << name2 << " : " << value2 << endl;  

  //输出到fd2
  cerr << name1 << " : " << value1 << endl;
  cerr << name2 << " : " << value2 << endl;  
  int x = atoi(value1.c_str());
  int y = atoi(value2.c_str());

  //模拟业务处理
  std::cout << "<html>";
  std::cout << "<head><meta charset=\"UTF-8\"></head>";
  std::cout << "<body>";
  std::cout << "<h3>" << value1 << " + " << value2 << " = " << x+y << "</h3>";
  std::cout << "<h3>" << value1 << " - " << value2 << " = " << x-y << "</h3>";
  std::cout << "<h3>" << value1 << " * " << value2 << " = " << x*y << "</h3>";
  std::cout << "<h3>" << value1 << " / " << value2 << " = " << x/y << "</h3>";
  std::cout << "</body>";
  std::cout << "</html>";
  return 0;
}
